importClass(java.lang.System);
var okHttp = require("./okHttp.js");
var _ = require("./lodash.js")
let down = {};
down.download = function(url, path, progress){

    okHttp.request(url, {method: 'GET'}, function(res, err){
        try{
            let $error = err;
        
        let $total = res._body.contentLength() || 0;
        if(!_.isFunction(_.get(res, '_body.byteStream'))){
            // return next({errcode: '1000-01'});
            
        }
        files.ensureDir(path); files.remove(path);
        
        let $stream = res._body.byteStream();
        try {
            let $buffer = util.java.array('byte', 2048 * 2);
            let $count = 0, $dif = 0;
            while(($len = $stream.read($buffer)) != -1) {
                let $buf_o = util.java.array('byte', $len);
                System.arraycopy($buffer, 0, $buf_o, 0, $len);
                files.appendBytes(path, $buf_o);
                $count += $len
                if(($count/$total - $dif) < 0.001){ continue; }
                $dif = $count/$total;
                progress($total, $count);
                // app.C.event.emit('apk_down_progress', args.name, (($count/$total) * 100).toFixed(2));
            }
            try { $stream.close(); } catch(e){}
        } catch(e){
            console.log(e)
            $error = e;
            try { $stream.close();} catch(e){}
        }
        progress($total, $total);
        // next($error, $_file_, res);
        }catch(e){
            console.log(e)
        }
    });

}
module.exports = down;

